package gov.child.dao.impl;

import gov.child.dao.AbstractDao;
import gov.child.dao.AjaxDao;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Optional;

/**
 * @author fzh
 * @since 2017/9/20
 */
@Repository("ajaxDao")
public class AjaxDaoImpl extends AbstractDao implements AjaxDao {

    @Override
    public Object findUsernameFromUser(String username) {
        Session session = currentSession();
        String sql = "SELECT username FROM user WHERE username = :username";
        Query query = session.createNativeQuery(sql).setParameter("username", username);
        Optional o = query.uniqueResultOptional();
        return o.isPresent() ? o.get() : null;
    }

    @Override
    public Object findPhoneFromUser(String phone) {
        Session session = currentSession();
        String sql = "SELECT username FROM user WHERE phone = :phone";
        Query query = session.createNativeQuery(sql).setParameter("phone", phone);
        Optional o = query.uniqueResultOptional();
        return o.isPresent() ? o.get() : null;
    }

    @Override
    public Object findUniqueResultBySql(String sql, Object... objects) {
        Session session = currentSession();
        Query query = session.createQuery(sql);
        for (int i = 0; i < objects.length; i++) {
            query.setParameter(i, objects[i]);
        }
        Optional o = query.uniqueResultOptional();
        return o.isPresent() ? o.get() : null;
    }

    @Override
    public Collection findMultiResultBySql(String sql, Object... objects) {
        Session session = currentSession();
        Query query = session.createQuery(sql);
        for (int i = 0; i < objects.length; i++) {
            query.setParameter(i, objects[i]);
        }
        Collection o = query.list();
        return o;
    }
}
